package com.leo.stopwatch;
/*Copyright (c) 2010-2012, Daniel Bostwick

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
3. Neither the name of Daniel Bostwick nor the names
   of its contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.*/
import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class Stopwatchcount extends Activity {

	Button m_tpButton, plus1, plus2, plus3, minus1, minus2, minus3;
	int seconds, hours, minutes, total;
	private static final int menu1 = 0;
	private static final int menu2 = 1;
	private static final int menu3 = 2;
	private long mRemainTime;
	DecimalFormat nf;
	private Button m_start;
	private Button m_pause;
	private Button m_reset;
	private Button m_resume;
	public static final String save = "save";
	public static final String hourcount = "hourcount";
	public static final String minutecount = "minutecount";
	public static final String secondcount = "secondcount";
	public static final String time = "time";
	TextView tv; // textview to display the countdown
	EditText edithours, editminutes, editseconds;
	MyCount counter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stopwatchcount);
		nf = new DecimalFormat("##");
		AdView adView = new AdView(this, AdSize.BANNER, "Publisher ID");
		LinearLayout layout = (LinearLayout) findViewById(R.id.AdLayout);
		layout.addView(adView);
		adView.loadAd(new AdRequest());

		edithours = (EditText) findViewById(R.id.hours);
		editminutes = (EditText) findViewById(R.id.minutes);
		editseconds = (EditText) findViewById(R.id.seconds);
		edithours.setOnKeyListener(new EditText.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				try {
					hours = Integer.parseInt(edithours.getText().toString());
					if (hours == 0) {
					}
				}
				// TODO Auto-generated method stub}
				catch (Exception obj) {
				}
				return false;
			}

		});
		editminutes.setOnKeyListener(new EditText.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				try {
					minutes = Integer
							.parseInt(editminutes.getText().toString());
					if (minutes == 0) {
					}
				} catch (Exception obj) {
				}
				return false;// TODO Auto-generated method stub
			}

		});
		editseconds.setOnKeyListener(new EditText.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				try {
					seconds = Integer
							.parseInt(editseconds.getText().toString());
					if (seconds == 0) {
					}
				} catch (Exception obj) {
				}
				return false;// TODO Auto-generated method stub
			}

		});

		m_pause = (Button) findViewById(R.id.PauseButton);
		m_reset = (Button) findViewById(R.id.ResetButton);
		m_resume = (Button) findViewById(R.id.resumeButton);
		tv = (TextView) findViewById(R.id.ElapsedTime);
		m_start = (Button) findViewById(R.id.StartButton);
		m_start.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 5000 is the starting number (in milliseconds)
				// 1000 is the number to count down each time (in milliseconds)
				total = ((hours * 60 * 60) + (minutes * 60) + (seconds)) * 1000;
				counter = new MyCount(total, 100);
				
				counter.start();
			}

		});
		m_pause.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			
				counter.cancel();
			}

		});
		m_reset.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				counter.cancel();
				tv.setText("0:0:0");

			}

		});
		m_resume.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				counter = new MyCount(mRemainTime, 100);

				counter.start();

			}

		});
		plus1 = (Button) findViewById(R.id.plus1);
		plus1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				hours = hours + 1;
				edithours.setText(nf.format(hours),
						TextView.BufferType.EDITABLE);
			}

		});
		minus1 = (Button) findViewById(R.id.minus1);
		minus1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				hours = hours - 1;
				edithours.setText(nf.format(hours),
						TextView.BufferType.EDITABLE);
			}

		});
		plus2 = (Button) findViewById(R.id.plus2);
		plus2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				minutes = minutes + 1;
				editminutes.setText(nf.format(minutes),
						TextView.BufferType.EDITABLE);
			}

		});
		minus2 = (Button) findViewById(R.id.minus2);
		minus2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				minutes = minutes - 1;
				editminutes.setText(nf.format(minutes),
						TextView.BufferType.EDITABLE);
			}

		});
		plus3 = (Button) findViewById(R.id.plus3);
		plus3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				seconds = seconds + 1;
				editseconds.setText(nf.format(seconds),
						TextView.BufferType.EDITABLE);
			}

		});
		minus3 = (Button) findViewById(R.id.minus3);
		minus3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				seconds = seconds - 1;
				editseconds.setText(nf.format(seconds),
						TextView.BufferType.EDITABLE);
			}

		});
		restorePrefs();
	}

	@Override
	protected void onStop() {
		try {
			super.onStop();

			// Save user preferences. use Editor object to make changes.
			SharedPreferences hoursettings = getSharedPreferences(save,
					MODE_PRIVATE);

			hoursettings.edit().putInt(hourcount, hours)
					.putInt(minutecount, minutes).putInt(secondcount, seconds)
					.commit();
		} catch (Exception obj) {
		}
	}

	private void restorePrefs() {

		try {
			SharedPreferences hoursettings = getSharedPreferences(save,
					MODE_PRIVATE);

			hours = hoursettings.getInt(hourcount, 0);
			minutes = hoursettings.getInt(minutecount, 0);
			seconds = hoursettings.getInt(secondcount, 0);
			edithours.setText(nf.format(hours), TextView.BufferType.EDITABLE);
			editminutes.setText(nf.format(minutes),
					TextView.BufferType.EDITABLE);
			editseconds.setText(nf.format(seconds),
					TextView.BufferType.EDITABLE);

		} catch (Exception obj) {
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, menu1, 0, (R.string.about)).setIcon(R.drawable.info);
		menu.add(0, menu2, 0, (R.string.exit)).setIcon(R.drawable.exit);
		menu.add(0, menu3, 0, (R.string.app)).setIcon(R.drawable.app);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case menu1:
			showAlertDialog("CEO/作者:Leo\nComments/評論:pcschoolleo@gmail.com\nIcons/圖示:www.iconfinder.com\n"
					+ "original source:https://github.com/bostwick/android-stopwatch\n"
					+ "original copyright:Daniel Bostwick");
			return true;
		case menu2:
			finish();
			return true;
		case menu3:
			Intent intenta = new Intent(Intent.ACTION_VIEW);
			intenta.setData(Uri.parse("market://search?q=pcschoolleo"));
			startActivity(intenta);
			return true;
		}
		return false;
	}

	private void showAlertDialog(String message) {
		new AlertDialog.Builder(this).setMessage(message)
				.setPositiveButton("ok", null).show();
	}

	// countdowntimer is an abstract class, so extend it and fill in methods
	public class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);

		}

		@Override
		public void onFinish() {
			tv.setText(R.string.done);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			mRemainTime = millisUntilFinished;
			tv.setText("" + ((millisUntilFinished / 1000) / 3600) + ":"
					+ (((millisUntilFinished / 1000) / 60) % 60) + ":"
					+ (millisUntilFinished / 1000) % 60 + "."
					+ (millisUntilFinished / 100) % 10);

		}

	}
}